package org.shark.colortheme.fragment;

import org.shark.colortheme.ColorThemeApplication;
import org.shark.colortheme.R;
import org.shark.colortheme.core.ColorStyle;
import org.shark.colortheme.core.ColorStyleObservable;
import org.shark.colortheme.core.ColorStyleObserver;
import org.shark.colortheme.core.StyleHelper;

import android.graphics.drawable.StateListDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;

public class SettingFragment extends Fragment implements OnClickListener , ColorStyleObserver{
	private View rootView;
	private LinearLayout layout_color;
	
	public static SettingFragment newInstance() {
		SettingFragment fragment = new SettingFragment();
		return fragment;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.root_ft_setting, container, false);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		rootView = getView();
		layout_color = (LinearLayout) rootView.findViewById(R.id.layout_color);
		layout_color.setOnClickListener(this);
		
		ColorStyle chage = ColorThemeApplication.getInstance().getColorStyle();
		StateListDrawable buttonStyle1 = StyleHelper
				.newSelector2(getActivity(), chage.getColor_normal(),
						chage.getColor_normal());
		layout_color.setBackgroundDrawable(buttonStyle1);
		ColorThemeApplication.getInstance().addStyleObserver(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layout_color:
			showColorPanel();
			break;

		default:
			break;
		}
	}
	
	private void showColorPanel() {
		FragmentTransaction ft = getActivity().getSupportFragmentManager()
				.beginTransaction();
		Fragment prev = getActivity().getSupportFragmentManager()
				.findFragmentByTag(ColorPanel.Tag);
		if (prev != null) {
			ft.remove(prev);
		}
		ft.addToBackStack(null);
		ColorPanel colorPanel = ColorPanel.newInstance();
		colorPanel.show(ft, ColorPanel.Tag);
	}

	@Override
	public void onChageColorStyle(ColorStyleObservable o, ColorStyle chage) {
		StateListDrawable buttonStyle1 = StyleHelper
				.newSelector2(getActivity(), chage.getColor_normal(),
						chage.getColor_normal());
		layout_color.setBackgroundDrawable(buttonStyle1);
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		ColorThemeApplication.getInstance().deleteStyleObserver(this);
	}
}
